package client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Created by Peter on 2017/7/4.
 */
public class Client {
    public boolean connect(int port, String host) {
        EventLoopGroup group = new NioEventLoopGroup();

        boolean isConnectSuccess = false;
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    //日志
                    ch.pipeline().addLast("decoder", new StringDecoder());
                    ch.pipeline().addLast("encoder", new StringEncoder());
                    ch.pipeline().addLast("logging", new LoggingHandler(LogLevel.INFO));
                    ch.pipeline().addLast(new ClientHandler());
                }
            });

            // 启动客户端
            ChannelFuture f = b.connect(host, port).sync(); // (5)

            f.channel().closeFuture().sync();

        } catch (Exception e) {
            isConnectSuccess = false;
//            logger.error(e.getMessage(), e);
        } finally {
            group.shutdownGracefully();
        }
        return isConnectSuccess;

    }

    public static void main(String[] args) {
        Client client = new Client();

        boolean isConnectSuccess = client.connect(8090, "localhost");

        System.out.println("isConnectSuccess:" + isConnectSuccess);

    }
}
